package com.emergency.examine.service.impl;


import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import com.emergency.examine.dao.ExamScoreDao;
import com.emergency.examine.dao.ExamStaffDao;
import com.emergency.examine.domain.ExamScore;
import com.emergency.examine.domain.ExamStaff;
import com.emergency.examine.service.ExamStaffService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ExamStaffServiceImpl implements ExamStaffService {
    private final static Logger logger = LoggerFactory.getLogger(ExamStaffServiceImpl.class);

    @Autowired
    private ExamStaffDao examStaffDao;

    @Autowired
    private ExamScoreDao examScoreDao;

    @Autowired
    private IdWorker idWorker;

    //添加考生信息
    @Override
    public String saveRecord(ExamStaff examStaff) {
        if (CommonUtils.isNullOrEmpty(examStaff.getId())) {
            examStaff.setId(idWorker.nextId());
            examStaff.setCreateTime(new Date());
        }
        //保存考生，考生成绩信息
        examStaffDao.save(examStaff);
        scoreSave(examStaff);
        return examStaff.getId().toString();
    }

    //获取成绩信息
    private void scoreSave(ExamStaff examStaff) {
        List<ExamScore> examScores = examStaff.getExamScores();
        if (!CommonUtils.isNullOrEmpty(examScores)) {
            examScores.forEach(examScore -> {
                examScore.setId(idWorker.nextId());
                examScore.setCreateTime(new Date());
                examScore.setExamStaff(examStaff);
            });
        }
        examScoreDao.saveAll(examScores);
    }


    //获取考生信息
    @Override
    public ExamStaff getInfo(Long staffId) {
        ExamStaff examStaff = examStaffDao.findById(staffId).orElse(null);
        if (CommonUtils.isNullOrEmpty(examStaff)) {
            logger.info("没有这个考生");
            return examStaff;
        }
        //获取成绩
        examStaff.setExamScores(examScoreDao.findAllByExamStaff(staffId));
        return examStaff;
    }

    //删除考生信息
    @Override
    public void del(Long staffId) {
        examScoreDao.deleteByExamStaffId(staffId);
        examStaffDao.deleteById(staffId);
    }

    //查询
    @Override
    public Page<ExamStaff> findList(Map searchMap, int page, int size) {
        Specification<ExamStaff> specification = createSpecification(searchMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return examStaffDao.findAll(specification, pageRequest);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<ExamStaff> createSpecification(Map searchMap) {

        return new Specification<ExamStaff>() {

            @Override
            public Predicate toPredicate(Root<ExamStaff> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                // 考生姓名
                if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                    predicateList.add(cb.like(root.get("name").as(String.class), "%" + (String) searchMap.get("name") + "%"));
                }
                // 编号
                if (searchMap.get("num") != null && !"".equals(searchMap.get("num"))) {
                    predicateList.add(cb.like(root.get("num").as(String.class), "%" + (String) searchMap.get("num") + "%"));
                }
                // 所属队
                if (searchMap.get("team") != null && !"".equals(searchMap.get("team"))) {
                    predicateList.add(cb.like(root.get("team").as(String.class), "%" + (String) searchMap.get("team") + "%"));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }
}
